# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def __init__(self):
        self.sum = 0
        self.sum_list = []
        self.result = []

    def pathSum(self, root, targetSum):
        """
        :type root: Optional[TreeNode]
        :type targetSum: int
        :rtype: List[List[int]]
        """
        if not root:
            return []

        self.targetSum = targetSum
        self.loop(root)
        return self.result

    def loop(self, node):
        self.sum += node.val
        self.sum_list.append(node.val)

        if not node.left and not node.right:
            if self.sum == self.targetSum:
                self.result.append(self.sum_list[:])
                return
            else:
                return

        if node.left:
            self.loop(node.left)
            self.sum -= node.left.val
            self.sum_list.pop()
        if node.right:
            self.loop(node.right)
            self.sum -= node.right.val
            self.sum_list.pop()
        return
